package util

import (
	"errors"
	"go-mall/common/enum"
	"time"

	"github.com/jinzhu/copier"
)

func CopyProperties(dst, src any) error {
	if err := copier.CopyWithOption(dst, src, copier.Option{
		IgnoreEmpty: true,
		DeepCopy:    true,
		Converters: []copier.TypeConverter{
			{
				SrcType: time.Time{},
				DstType: copier.String,
				Fn: func(src interface{}) (dst interface{}, err error) {
					s, ok := src.(time.Time)
					if !ok {
						return nil, errors.New("not time.Time")
					}
					return s.Format(enum.TimeFormatHyphenedYMDHIS), nil
				},
			},
			{
				SrcType: copier.String,
				DstType: time.Time{},
				Fn: func(src interface{}) (dst interface{}, err error) {
					s, ok := src.(string)
					if !ok {
						return nil, errors.New("not string")
					}
					t, err := time.Parse(enum.TimeFormatHyphenedYMDHIS, s)
					if err != nil {
						return nil, errors.New("parse time error")
					}
					return t, nil
				},
			},
		},
	}); err != nil {
		return err
	}
	return nil
}
